#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''

import os,time,socket,threading
from com.zxy.adminlog.UsAdmin_Log import UsAdmin_Log
from com.zxy.business.Query_Data import Query_Data
from com.zxy.common import Com_Para
from com.zxy.common.Com_Fun import Com_Fun
from com.zxy.common.EncryptUtil import EncryptUtil
from com.zxy.model.Return_Value import Return_Value
from com.zxy.tcp.Request import Request
from openpyxl.descriptors.base import Length
from com.zxy.z_debug import z_debug
class ServerHandlerHttp(z_debug):
    attServSocket = None
    attStrIP = "0.0.0.0"
    attReturn_Value = Return_Value()
    attConnection = ""
    def __init__(self):
        pass
    def run(self):
        self.server_link()
    def server_link(self):
        Com_Para.socket_count = Com_Para.socket_count + 1
        if Com_Para.driverClassName == "org.sqlite.JDBC":
            self.init()
        else:
            self.init()
        Com_Para.socket_count = Com_Para.socket_count - 1
    def webPage_Real(self,inputStrUrl,inputS_guid,inputPost_str,inputQuery_Data,inputReturnMessage,inputWeb_name):
        temFilePath = Com_Para.ApplicationPath +Com_Para.zxyPath+ "web"
        if inputWeb_name == ".log":
            temFilePath = Com_Para.ApplicationPath
        if inputStrUrl[0:10] =="/root_api/":
            temFUrl = inputStrUrl[10:inputStrUrl.index(inputWeb_name)]
        else:
            temFUrl = inputStrUrl[0:inputStrUrl.index(inputWeb_name)]
        temFilePath = temFilePath + Com_Para.zxyPath+temFUrl
        temFilePath = temFilePath + inputWeb_name        
        if os.path.exists(temFilePath):
            bVue = False
            if inputStrUrl.find(".vue") != -1 and inputStrUrl.find(".vue") == len(inputStrUrl) - 4:
                bVue = True
            temFile = None
            try:
                temFile = open(file=temFilePath,mode='rb')                
                self.attServSocket.send((inputReturnMessage +"\r\n\r\n").encode(Com_Para.U_CODE))
                if bVue:
                    self.attServSocket.send(b'ReadCommonRes("')
                while True:
                    byt = temFile.read(1024)# 每次读取1024个字节
                    if bVue :
                        self.attServSocket.send(byt.replace(b'\t',b'').replace(b'\n',b'').replace(b'\r',b'').replace(b'\"',b'\\\"').replace(b'$',b'"'))
                    else:
                        self.attServSocket.send(byt)#字节形式发送数据                    
                    if not byt: #如果没有读到数据，跳出循环
                        break
                if bVue:
                    self.attServSocket.send(b'");')
                self.attServSocket.send("\r\n".encode(Com_Para.U_CODE))                
            except Exception as e:
                if str(type(self)) == "<class 'type'>":
                    self.debug_in(self,repr(e))#打印异常信息
                else:
                    self.debug_in(repr(e))#打印异常信息
            finally:
                if not temFile is None:
                    temFile.close()
        else:
            temErrorMessage = "HTTP/1.1 404 File Not Found\r\n"
            temErrorMessage += "Content-Type: text/html\r\n"
            temErrorMessage += "Content-Length: 230\r\n"
            temErrorMessage += "\r\n" + "<h1>未找到正确页面</h1>"
            try:
                self.attServSocket.send(temErrorMessage.encode(Com_Para.U_CODE))
                self.attServSocket.send("\r\n".encode(Com_Para.U_CODE))
            except Exception as e:
                pass
    def SubAnalyseRecBytes(self,temRequest):
        temS_guid = "" 
        temRequest.parse()
        self.attConnection = temRequest.attConnection
        temStrUrl = temRequest.attUri
        temPost_Str = temRequest.attPost_str
        self.attReturn_Value = temRequest.attRv        
        temReturnMessage = "HTTP/1.1 200 OK\r\n"
        if temStrUrl.find(".html") != -1 and temStrUrl.find(".html") == len(temStrUrl) - 5:
            temReturnMessage += "Content-Type: text/html\r\n"
        elif temStrUrl.find(".js") != -1 and temStrUrl.find(".js") == len(temStrUrl) - 3:
            temReturnMessage += "Content-Type: application/x-javascript\r\n"
        elif temStrUrl.find(".css") != -1 and temStrUrl.find(".css") == len(temStrUrl) - 4:
            temReturnMessage += "Content-Type: text/css\r\n"
        elif temStrUrl.find(".jpg") != -1 and temStrUrl.find(".jpg") == len(temStrUrl) - 4:
            temReturnMessage += "Content-Type: image/jpg\r\n"
        elif temStrUrl.find(".gif") != -1 and temStrUrl.find(".gif") == len(temStrUrl) - 4:
            temReturnMessage += "Content-Type: image/jpg\r\n"
        elif temStrUrl.find(".png") != -1 and temStrUrl.find(".png") == len(temStrUrl) - 4:
            temReturnMessage += "Content-Type: mage/png\r\n"
        elif temStrUrl.find(".svg") != -1 and temStrUrl.find(".svg") == len(temStrUrl) - 4:
            temReturnMessage += "Content-Type: text/svg+xml\r\n"
        elif temStrUrl.find(".eot") != -1 and temStrUrl.find(".eot") == len(temStrUrl) - 4:
            temReturnMessage += "Content-Type: application/vnd.ms-fontobject\r\n"
        elif temStrUrl.find(".ttf") != -1 and temStrUrl.find(".ttf") == len(temStrUrl) - 4:
            temReturnMessage += "Content-Type: application/x-font-ttf\r\n"
        elif temStrUrl.find(".woff") != -1 and temStrUrl.find(".woff") == len(temStrUrl) - 5:
            temReturnMessage += "Content-Type: application/x-font-woff\r\n"
        elif temStrUrl.find(".woff2") != -1 and temStrUrl.find(".woff2") == len(temStrUrl) - 6:
            temReturnMessage += "Content-Type: application/x-font-woff\r\n"
        elif temStrUrl.find(".ico") != -1 and temStrUrl.find(".ico") == len(temStrUrl) - 4:
            temReturnMessage += "Content-Type: image/ico\r\n"                
        elif temStrUrl.find(".log") != -1 and temStrUrl.find(".log") == len(temStrUrl) - 4:
            temReturnMessage += "Content-Type: text\r\n"
        elif temStrUrl.find(".vue") != -1 and temStrUrl.find(".vue") == len(temStrUrl) - 4:
            temReturnMessage += "Content-Type: application/x-javascript\r\n"
        else:
            temReturnMessage += "Content-Type: text/html\r\n"
        temReturnMessage += "Access-Control-Allow-Methods: POST,GET\r\n"
        temReturnMessage += "Access-Control-Allow-Origin:*" + Com_Para.HttpUrl
        temReturnMessage += "\r\n" + "Connection: Keep-Alive"
        temStrResult = "-1"
        temGd = Query_Data(self.attReturn_Value)
        bWeb_Name =  False
        for temAttF in Com_Para.web_Name:
            if temStrUrl.find(temAttF) != -1 and temStrUrl.find(temAttF) == len(temStrUrl) - len(temAttF) and temStrUrl.find("param_name=") == -1:
                self.webPage_Real(temStrUrl,temS_guid,temPost_Str,temGd,temReturnMessage,temAttF)
                bWeb_Name = True
                break
        if bWeb_Name == True or temRequest.attUploadFile != "":
            pass
        elif temStrUrl.find("sub_code=") != -1 and temStrUrl.find("param_name=") != -1:                
            temStrResult = self.Center_Data_Rel(temStrUrl,temS_guid,temPost_Str,temGd,temReturnMessage,temRequest.attStrIP[0])
        elif temStrUrl.strip() == "" and temStrUrl.strip().find("GET /favicon.ico HTTP/1.1") != -1:                
            temStrResult = self.Send_Error(temStrUrl,temS_guid,temPost_Str,temGd,temReturnMessage)
        elif temStrUrl.strip() != "":
            self.attServSocket.send((temReturnMessage+"\r\n\r\n请求错误接口或页面\r\n").encode(Com_Para.U_CODE))
        if temRequest.attUploadFile != "":
            self.attServSocket.send((temReturnMessage + "\r\n\r\n" + temRequest.attUploadFile  + "\r\n").encode(Com_Para.U_CODE))              
        elif temStrResult != "-1":
            self.attServSocket.send((temReturnMessage + "\r\n\r\n" + temStrResult + "\r\n").encode(Com_Para.U_CODE))              
        return temReturnMessage
    def init(self):
        try:
            temRequest = Request()
            temRequest.attServSocket = self.attServSocket
            temRequest.attStrIP = self.attStrIP
            self.attServSocket.setblocking(1)
            temReturnMessage = self.SubAnalyseRecBytes(temRequest)
        except Exception as e:
            self.attServSocket.send(temReturnMessage+"\r\n\r\n"+repr(e)+"\r\n".encode(Com_Para.U_CODE))
            temLog = ""
            if str(type(self)) == "<class 'type'>":
                temLog = self.debug_info(self)+repr(e)
                self.debug_in(self,repr(e))#打印异常信息
            else:
                temLog = self.debug_info()+repr(e)
                self.debug_in(repr(e))#打印异常信息
            uL = UsAdmin_Log(Com_Para.ApplicationPath, temLog)
            uL.WriteLog()            
        finally:
            self.attServSocket.shutdown(1)
            self.attServSocket.close()
            pass
    def Send_Error(self,inputStrUrl,inputS_guid,inputPost_Str,inputGd,inputReturnMessage):
        inputReturnMessage = "Error请求语法错误"
        return inputReturnMessage
    def Center_Data_Rel(self,inputStrUrl, inputS_guid, inputPost_Str, inputGd, inputReturnMessage, inputStrIP):
        temStrAry = ""
        temHtParam = {}
        for temStrTemV in inputStrUrl.split("&"):
            temStrTemPar = temStrTemV.split("=")
            if len(temStrTemPar) == 2:
                Com_Fun.SetHashTable(temHtParam,temStrTemPar[0],temStrTemPar[1])
            else:
                Com_Fun.SetHashTable(temHtParam,temStrTemPar[0],"")
        temSub_code = Com_Fun.GetHashTable(temHtParam,"sub_code")
        temSub_usercode = Com_Fun.GetHashTable(temHtParam,"sub_usercode")
        temDelay_data = Com_Fun.GetHashTable(temHtParam,"delay_data")
        temDelay_code = Com_Fun.GetHashTable(temHtParam,"delay_code")
        temParam_name = Com_Fun.GetHashTable(temHtParam,"param_name")
        temSession_id = Com_Fun.GetHashTable(temHtParam,"session_id")
        temJsoncallback = Com_Fun.GetHashTable(temHtParam,"jsoncallback")
        self.attReturn_Value.attParam_name = temParam_name
        temBFlag = False
        if Com_Para.Is_UserLogin != "" and (Com_Para.Is_UserLogin.find("[" + temParam_name + "]") != -1 or Com_Para.Is_UserLogin.find("%5B" + temParam_name + "%5D") != -1) :
            temBFlag = True
        temAryParamValue = []
        for i in range(1,101):
            temInbFlag = False
            temStrVS = ""
            if not Com_Fun.GetHashTableNone(temHtParam,"param_value" + str(i)) is None:
                temStrVS = Com_Fun.GetHashTable(temHtParam,"param_value" + str(i))
                if i == 1 or i == 2:
                    temStrVS = Com_Fun.getParam_value1(temStrVS.strip())
                temInbFlag = True
            else:
                for temTemstr in inputPost_Str:
                    if temTemstr.strip().find("param_value" + str(i) + "=") == 0:
                        temInbFlag = True
                    elif temTemstr == "jsonpzxyong":
                        temJsoncallback = temTemstr.split("=")[1]
                    if temTemstr.strip().find("param_value" + str(i) + "=") == 0 and len(temTemstr.split("=")) > 1:
                        temStrVS = temTemstr.split("=")[1]
                        if i == 1 or i == 2:
                            temStrVS = Com_Fun.getParam_value1(temStrVS.strip())
                        break
            if not temInbFlag:
                break
            if temBFlag and i == 2:
                if Com_Para.EncryptUtilType == 1:
                    temStrVS = EncryptUtil.getSM32(temStrVS)
                elif Com_Para.EncryptUtilType == 2:
                    temStrVS = EncryptUtil.getMd5(temStrVS).lower()
                elif Com_Para.EncryptUtilType == 3:
                    temStrVS = EncryptUtil.getSha1(temStrVS)
            temAryParamValue.append(temStrVS)
        if temBFlag:
            inputGd.attSession_id = Com_Fun.Get_New_GUID()
            temStrAry = inputGd.GetDataList(temSub_code,temSub_usercode,temParam_name,temAryParamValue,inputStrUrl,temDelay_data,temDelay_code,inputStrIP,temHtParam)
        elif Com_Para.Login_Session == 1 and Com_Fun.GetInterSession(temParam_name):
            inputGd.attSession_id = temSession_id
            if Com_Fun.GetInterSession(temParam_name):
                if temSession_id == "" or not Com_Fun.HadSession(temSession_id,temSession_id):
                    temStrAry = "{\""+ temParam_name+ "\":[{\""+Com_Fun.GetLowUpp("session_id")+"\":\"\",\""+Com_Fun.GetLowUpp("s_result")+"\":\"0\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"用户未登陆,请登陆\"}]}"
                else:
                    temStrAry = inputGd.GetDataList(temSub_code,temSub_usercode,temParam_name,temAryParamValue,inputStrUrl,temDelay_data,temDelay_code,inputStrIP,temHtParam)
            else:
                temStrAry = inputGd.GetDataList(temSub_code,temSub_usercode,temParam_name,temAryParamValue,inputStrUrl,temDelay_data,temDelay_code,inputStrIP,temHtParam)
        else:
            inputGd.attSession_id = temSession_id
            temStrAry = inputGd.GetDataList(temSub_code,temSub_usercode,temParam_name,temAryParamValue,inputStrUrl,temDelay_data,temDelay_code,inputStrIP,temHtParam)
        if temJsoncallback != "":
            temStrAry = temJsoncallback + "("+temStrAry+")"
        if self.attReturn_Value.attS_result == 1:
            self.attReturn_Value = inputGd.attReturn_Value        
        temHtParam = None        
        return temStrAry